<template>
	<view v-if="queue.count" class="queue flex-column">
		<view class="text">
			当前客服繁忙，您已进入排队队列，当前处于第 <text class="count">{{ queue.count }}</text> 位
			<template v-if="config?.isQueueCountDown">，预计等待时间约 <text class="count">{{ duration }}</text></template>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'

const timer = ref(null)
const duration = ref('')
const props = defineProps({
	config: { type: Object, default: () => { } },
	queue: {
		type: Object, 
		default: () => ({
			count: 0,
			duration: 0
		})
	},
})

// 格式化时间
function formatDuration(totalSeconds : number) {
	const minutes = Math.floor(totalSeconds / 60)
	const seconds = totalSeconds % 60
	if (minutes && seconds) {
		duration.value = `${minutes}分${seconds}秒`
	} else if (minutes) {
		duration.value = `${minutes}分钟`
	} else {
		duration.value = `${seconds}秒`
	}
}

watch(() => props.queue, () => {
	// 不显示倒计时时不执行
	if (!props.config?.isQueueCountDown) return

	if (timer.value) {
		clearInterval(timer.value)
	}

	let totalSeconds = props.queue.duration
	formatDuration(totalSeconds)
	timer.value = setInterval(() => {
		totalSeconds--
		if (totalSeconds < 1) {
			clearInterval(timer.value)
		}
		formatDuration(totalSeconds)
	}, 1000)
}, { deep: true, immediate: true })
</script>

<style lang="scss" scoped>
.queue {
	width: 100%;

	.text {
		color: #666;
		margin: 20rpx 10%;
		font-size: 24rpx;
		padding: 16rpx 30rpx;
		border-radius: 10rpx;
		text-align: center;
		background: #eee;
		display: inline-block;
		
		.count {
			font-weight: bold;
		}
	}
}
</style>